<?

/////////
// I am antiquated. Avoid calling functions in me.
/////////

/////////////////////////////////////////////////
// Constants that are names for things.
/////////////////////////////////////////////////

$abspath = "/tbatv/";

//long names for different match levels
$complevelnames["00"] = "Misc";
$complevelnames["10"] = "Qualifications";
$complevelnames["20"] = "Eighths";
$complevelnames["30"] = "Quarters";
$complevelnames["40"] = "Semis";
$complevelnames["50"] = "Finals";
//long names for different match levels
$complevelnouns["00"] = "???";
$complevelnouns["10"] = "Participants";
$complevelnouns["20"] = "Eigth Finalists";
$complevelnouns["30"] = "Quarterfinalists";
$complevelnouns["40"] = "Semifinalists";
$complevelnouns["50"] = "Finalists";
$complevelnouns["60"] = "Champions";
//short names for different match levels, !!defines naming convention for files!!
$complevelshort["0"] = "misc";
$complevelshort["10"] = "q";
$complevelshort["20"] = "ef";
$complevelshort["30"] = "qf";
$complevelshort["40"] = "sf";
$complevelshort["50"] = "f";
//names of weeks, the database variable.
$weeknames["-1"] = "Invalid";
$weeknames["0"] = "Pre-Ship";
$weeknames["10"] = "Week 1";
$weeknames["20"] = "Week 2";
$weeknames["30"] = "Week 3";
$weeknames["40"] = "Week 4";
$weeknames["50"] = "Week 5";
$weeknames["60"] = "Week 6";
$weeknames["90"] = "World Championships - Divisons";
$weeknames["91"] = "World Championships - Finals";
$weeknames["100"] = "Offseason";
//images corresponding to week, based on google maps key.
$weekimages["0"] = "<img src=\"images/GREYMarkersmall.png\" />";
$weekimages["10"] = "<img src=\"images/ORANGEMarkersmall.png\" />";
$weekimages["20"] = "<img src=\"images/REDMarkersmall.png\" />";
$weekimages["30"] = "<img src=\"images/PURPLEMarkersmall.png\" />";
$weekimages["40"] = "<img src=\"images/BLUEMarkersmall.png\" />";
$weekimages["50"] = "<img src=\"images/GREENMarkersmall.png\" />";
$weekimages["60"] = "<img src=\"images/PINKMarkersmall.png\" />";
$weekimages["90"] = "<img src=\"images/YELLOWMarkersmall.png\" />";
$weekimages["91"] = "<img src=\"images/YELLOWMarkersmall.png\" />";
$weekimages["100"] = "<img src=\"images/GREYMarkersmall.png\" />";

//defines week start and end dates
$week_definitions["2008"] = array("10" => array("2008-02-28", "2008-03-02"),
																	"20" => array("2008-03-06", "2008-03-09"),
																	"30" => array("2008-03-13", "2008-03-16"),
																	"40" => array("2008-03-20", "2008-03-23"),
																	"50" => array("2008-03-27", "2008-03-30"),
																	"60" => array("2008-04-04", "2008-04-07"),
																	"90" => array("2008-04-17", "2008-04-20"));

//no SQL injection!
function sanatizeGet($value) {
	$output = htmlentities(stripslashes($value));
	return $output;
}

//Page needs to die early.
function bomb_in_middle($error_msg) {
	include "header.php";
	echo $error_msg;
	include "footer.php";
	exit();
}

//////////////////////////////////////////////////////
// Functions that quick generate constantly used things
//////////////////////////////////////////////////////

//buildlocation
//takes a city, state, and country, and builds the location.
function buildlocation($city, $state, $country) {
	$state = str_replace(",", "", $state);
	$location = "$city";
	if ($state != NULL AND $state != '') $location = $location . ", $state";
	if ($country != NULL AND $country != '') $location = $location . ", $country";
	return $location;
}

//generates a hyperlink to a team's page, or a questionmark if we don't have a team.
function teamlink($teamnumber, $link) {
	if ($teamnumber == 0) {
		return "?";
	} else if ($link == 1) {
		return "<a href=\"team.php?team={$teamnumber}\" title=\"Information On Team {$teamnumber}\">{$teamnumber}</a>";
	} else {
		return $teamnumber;
	}
}

//returns the path to a video.
function videopath($eventshort, $year, $complevel, $matchnumber, $extension) {
	//import global dictionaries
	global $complevelnames, $complevelshort, $weeknames;
	//truncate year from YYYY to YY
	$yearshort = str_pad($year - 2000, 2, "0", STR_PAD_LEFT); //this will only work until 2100.
	
	//establish foldertree
	$root = "vids/";
	$dir = "{$yearshort}{$eventshort}/";
	
	//correct for database storage technique. Finals don't have the "1x" they should.
	if ($complevel == 50 AND $matchnumber < 10) $matchnumber+=10;
	
	//shift match number if its an elim.
	if ($complevel > 10) {
		$setnumber = floor($matchnumber / 10);
		$matchnumber = $matchnumber - $setnumber * 10;
	}
	
	//produce filename.
	$filename = "{$eventshort}_{$complevelshort[$complevel]}{$setnumber}m{$matchnumber}.{$extension}";
	
	//return path and name.
	return $root . $dir . $filename;
}

//returns the name for a match
function matchname($complevel, $matchnumber) {

	//import global dictionaries
	global $complevelnames, $complevelshort, $weeknames;
	
	if ($complevel == 10) {
		$matchnumber_output = $matchnumber;
	}
	
	//echo elim info
	if ($complevel > 10) {
		$matchnumber_output = " " . floor($matchnumber / 10) . " Match " . ($matchnumber - floor($matchnumber / 10) * 10);
	}
	
	//correct for database storage technique. Some finals don't have the "1x" they should.
	if ($complevel == 50 AND $matchnumber < 10) $matchnumber+=10;
	if ($complevel == 50) {
		$matchnumber_output = " Match " . ($matchnumber-10);
	}
	
	//return match name
	return "{$complevelnames[$complevel]} {$matchnumber_output}";
}

function playerBracket($r) {
	echo "[";
	if ($r["redscore"] > $r["bluescore"]) echo "<strong>";
	echo "<span style=\"color: #ff4444\">" . teamlink($r["red1"],0) . " - " . teamlink($r["red2"],0) . " - " . teamlink($r["red3"],0) . "</span>";
	if ($r["redscore"] > $r["bluescore"]) echo "</strong>";
	echo " vs. ";
	if ($r["bluescore"] > $r["redscore"]) echo "<strong>";
	echo "<span style=\"color: #4444ff\">" . teamlink($r["blue1"],0) . " - " . teamlink($r["blue2"],0) . " - " . teamlink($r["blue3"],0) . "</span>]";
	if ($r["bluescore"] > $r["redscore"]) echo "</strong>";
}

//////////////////////
// Awards & Misc Video supporting Functions
//////////////////////

function getAwardWinners($eventid=0, $team=0, $year=0) {
	if ($eventid == 0) {
		if ($team == 0) {
			return false;
		} else {
			if ($year == 0) {
				$award_query_filter = "SELECT * FROM awards, awardwinners WHERE team = '$team' AND awards.awardid = awardwinners.award";
			} else {
				$award_query_filter = "SELECT * FROM awards, awardwinners WHERE team = '$team' AND year='$year' AND awards.awardid = awardwinners.award";
			}
		}
	} else {
		if ($team == 0) {
			$award_query_filter = "SELECT * FROM awards, awardwinners WHERE event = '$eventid' AND awards.awardid = awardwinners.award";
		} else {
			$award_query_filter = "SELECT * FROM awards, awardwinners WHERE event = '$eventid' AND team = '$team' AND awards.awardid = awardwinners.award";
		}
	}
	
	$awardinfo_query = mysql_query($award_query_filter);
	
	
	return $awardinfo_query;
}

function printAwardInfo($awardinfo_query) {
	printf("<table class=\"table_alt\">\r");
	printf("<tr class=\"table_toprow\"><td><img src=\"images/video_icon.png\" /></td><td>Award</td><td>Team</td><td>Recipiant</td></tr>\r");
	$i = 0;
	while ($awardinfo = mysql_fetch_array($awardinfo_query)) {
		if ($awardinfo["team"] == 0) $awardinfo["team"] = "";
		if ($awardinfo["flvup"] ==1) {
			$videostring = "<a href=\"http://www.google.com\"><img src=\"images/video_icon.png\" /></a>";
		} else {
			$videostring = "";
		}
		//set up table row
		printf("<tr class=\"table_row%s\">", ($i & 1));
		$i++;
		printf("<td>%s</td><td><strong>%s</strong></td><td><strong><a href=\"team.php?team=%s\">%s</a></strong></td><td>%s</td></tr>\r",
					$vieostring, $awardinfo["name"], $awardinfo["team"], $awardinfo["team"], $awardinfo["person"]);

	}
	printf("</table>");
}

//////////////////////
// Elims Bracket Generation Functions
//////////////////////

//return what teams played in, and who won, a given set of elim matches
function whowon($eventid, $complevel, $setnumber) {
	global $complevelnames, $complevelshort, $weeknames;
	
	$setlow = $setnumber * 10 - 1;
	$sethigh = ($setnumber + 1) * 10;
	
	//look up what event we're dealing with
	$matchinfo_query_filter = "SELECT * FROM `matches` WHERE `event`='$eventid' AND `complevel`='$complevel' AND `matchnumber` > $setlow AND `matchnumber` < $sethigh ORDER BY `matchnumber` DESC LIMIT 1";
	$matchinfo_query = mysql_query($matchinfo_query_filter);
	$matchinfo = mysql_fetch_array($matchinfo_query);
	
	$returnvalue["red1"] = $matchinfo["red1"];
	$returnvalue["red2"] = $matchinfo["red2"];
	$returnvalue["red3"] = $matchinfo["red3"];
	$returnvalue["blue1"] = $matchinfo["blue1"];
	$returnvalue["blue2"] = $matchinfo["blue2"];
	$returnvalue["blue3"] = $matchinfo["blue3"];
	
	if ($matchinfo["redscore"] > $matchinfo["bluescore"]) {
		$returnvalue["winner"] = "red";
	} elseif ($matchinfo["redscore"] < $matchinfo["bluescore"]) {
		$returnvalue["winner"] = "blue";
	} else {
		$returnvalue["winner"] = "tie";
	}	
	
	return $returnvalue;
}

//make whowon look pretty.
function formatwhowon($whowon, $color, $rowspan, $LR) {
	//abort if no info.
	if (isset($whowon["red1"])) {
		if ($color == $whowon["winner"]) $winnerclass = " winner" . $LR;
		if ($color != $whowon["winner"] AND $LR == "C") $winnerclass = " secondC";
		echo "<td class=\"{$color}{$winnerclass}\" rowspan=\"$rowspan\">";
		
		if ($color == $whowon["winner"]) echo "<strong>";
		if ($color == "red") echo teamlink($whowon["red1"],1) . "<br />" . teamlink($whowon["red2"],1) . "<br />" . teamlink($whowon["red3"],1);
		if ($color == "blue") echo teamlink($whowon["blue1"],1) . "<br />" . teamlink($whowon["blue2"],1) . "<br />" . teamlink($whowon["blue3"],1);
		if ($color == $whowon["winner"]) echo "</strong>";
		
		echo "</td>";
	}
}

//generate the whole elims bracket.
function generateElimsBracket($eventid) {
	?>
	<table class="brackettable" cellspacing="0">
	<tr><td colspan="6" class="header">Eliminations Bracket</td></tr>
	
	<tr><? formatwhowon(whowon($eventid, 30, 1), "red", 1, "L") ?><? formatwhowon(whowon($eventid, 40, 1), "red", 2, "L") ?><? formatwhowon(whowon($eventid, 50, 1), "red", 4,"C") ?><? formatwhowon(whowon($eventid, 50, 1), "blue",4,"C") ?><? formatwhowon(whowon($eventid, 40, 2), "blue",2,"R") ?><? formatwhowon(whowon($eventid, 30, 4), "red", 1,"R") ?></tr>
	
	<tr><? formatwhowon(whowon($eventid, 30, 1), "blue", 1,"L") ?><? formatwhowon(whowon($eventid, 30, 4), "blue", 1,"R") ?></tr>
	
	<tr><? formatwhowon(whowon($eventid, 30, 2), "red", 1,"L") ?><? formatwhowon(whowon($eventid, 40, 1), "blue", 2,"L") ?><? formatwhowon(whowon($eventid, 40, 2), "red", 2,"R") ?><? formatwhowon(whowon($eventid, 30, 3), "red", 1,"R") ?></tr>
	
	<tr><? formatwhowon(whowon($eventid, 30, 2), "blue", 1,"L") ?><? formatwhowon(whowon($eventid, 30, 3), "blue", 1,"R") ?></td></tr>
	</table>
	<?
}

function bulkeventinfo($year = NULL) {
	//handle optional args
	if ($year == NULL) $year = date('Y');
	
	global $weeknames, $weekimages;

	printf("<table class=\"table_alt\">\r");		
	foreach($weeknames as $weeknumber => $weekname) {
		
		//look up what we're dealing with
		$eventinfo_query_filter = "SELECT COUNT(*) as \"teamsregistered\", events.* FROM attendance, events WHERE events.year = $year AND events.week = $weeknumber AND attendance.event = events.eventid GROUP BY events.eventid;";
		$eventinfo_query = mysql_query($eventinfo_query_filter);
		
		if (mysql_num_rows($eventinfo_query) > 0) {
			printf('<tr class="table_toprow" id="week%s"><td colspan="5">%s %s %s</td></tr>', $weeknumber, $weekimages[$weeknumber], $weeknames[$weeknumber], $weekimages[$weeknumber]);
			printf('<tr class="table_toprow"><td>Teams</td><td>Videos</td><td>Name</td><td>Location</td><td>Site</td></tr>');
		
			//iterate the results
			$i = 0;
			while ($event = mysql_fetch_array($eventinfo_query)) {
				//set up table row
				printf("<tr class=\"table_row%s\">", ($i & 1));
				$i++;
				
				//count teams attending
				$teamsattending = $event["teamsregistered"];
				
				//count videos online
				$videos_query_filter = "SELECT COUNT(matches.flvup) FROM matches WHERE matches.event={$event["eventid"]} AND matches.flvup = 1";
				$videos_query = mysql_query($videos_query_filter);
				$videosonline = mysql_fetch_array($videos_query);
				$videosonline = $videosonline[0];
				
				
				//decide on website
				if ($team["website"] != '') {
					$website = "<a href=\"{$event["website"]}\" title=\"{$event["name"]}\" target=\"_blank\"><img src=\"images/globe.png\"></a>";
				} else {
					$website = '';
				}
										
				//spit it out
				printf("<td><strong>%s</strong></td><td><strong>%s</strong></td><td><strong><a href=\"event.php?eventid=%s\">%s</a></strong></td><td>%s</td><td>%s</td></tr>\r",
					$teamsattending, $videosonline, $event["eventid"], $event["name"], $event["location"], $website);
			}
		}
	}
	printf("</table>");
	return TRUE;
}

function teamsattending($eventid) {
	$eventinfo_query_filter = "SELECT COUNT(*) as \"teamsregistered\", events.eventid FROM attendance, events WHERE events.eventid = '$eventid' AND attendance.event = events.eventid GROUP BY eventid;";
	$eventinfo_query = mysql_query($eventinfo_query_filter);
	$event = mysql_fetch_array($eventinfo_query);
	return $event["teamsregistered"];
}

/////////////////////
// Team Information Functions
/////////////////////

function teaminfo($teamnumber) {
	//look up what we're dealing with
	$teaminfo_query_filter = "SELECT * FROM teams WHERE teamnumber=$teamnumber LIMIT 1";
	$teaminfo_query = mysql_query($teaminfo_query_filter);
	
	if (mysql_num_rows($teaminfo_query) == 0) {
		$teaminfo = 0;
	} else {
		$teaminfo = mysql_fetch_array($teaminfo_query);
	}
	
	return $teaminfo;
}

// bulkteaminfo
// Performs an SQL database call to pull out team info for several teams at once. Returns FALSE if there were no teams.
function bulkteaminfo($filterstring, $year = NULL) {
	//handle optional args
	if ($year == NULL) $year = date('Y');

	//look up what we're dealing with
	$teaminfo_query_filter = "SELECT teams.*, attendance.* FROM attendance, teams WHERE $filterstring";
	$teaminfo_query = mysql_query($teaminfo_query_filter);

	if (mysql_num_rows($teaminfo_query) == 0) {
		return FALSE;
	} else {
		printf("<table class=\"table_alt\">\r<tr class=\"table_toprow\"><td>#</td><td><img src=\"images/camera_icon.png\" /></td><td>Name</td><td>Location</td><td>Site</td></tr>");
		//iterate the results
		$i = 0;
		while ($team = mysql_fetch_array($teaminfo_query)) {
			//set up table row
			printf("<tr class=\"table_row%s\">", ($i & 1));
			$i++;
			
			//decide on website
			if ($team["website"] != '') {
				$website = "<a href=\"{$team["website"]}\" title=\"{$team["informalname"]}\" target=\"_blank\"><img src=\"images/globe.png\"></a>";
			} else {
				$website = '';
			}
			
			//decide on photo
			if (file_exists("pictures/$year/{$team["teamnumber"]}.jpg")) {
				$photo = "<a href=\"pictures/$year/" . $team["teamnumber"] . ".jpg\" rel=\"lightbox['teams']\" title=\"Team {$team["team"]} - $year\"><img src=\"images/camera_icon.png\" /></a>";
			} else {
				$photo = '';
			}
			
			//decide on location
			$teamlocation = buildlocation($team["city"], $team["state"], $team["country"]);
			
			//decide on team name
			if ($team["informalname"] == '' OR $team["informalname"] == NULL) {
				$teamname = $team["name"];
			} else {
				$teamname = "<strong>" . $team["informalname"] . "</strong>";
			}
			
			//spit it out
			printf("<td><strong>%s</strong></td><td>%s</td><td><a href=\"team.php?team=%s&year=%s\">%s</a></td><td>%s</td><td>%s</td></tr>\r",
				$team["teamnumber"], $photo, $team["teamnumber"], $year, $teamname, $teamlocation, $website);
		}
		printf("</table>");
	}
	return TRUE;
}

/////////////////////
// Match Information Functions
/////////////////////

function getWLT($span, $id, $teamnumber) {
	//$span can be "quals", "elims", "event", "year", "alltime"
	//$id contains the eventid, year, or a value that doesn't matter.
	
	switch($span) {
		case "quals":
			$win_query_filter = "SELECT * FROM matches WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber) AND redscore > bluescore) OR ((blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber) AND bluescore > redscore)) AND complevel = 10 AND event = $id";
			$lose_query_filter = "SELECT * FROM matches WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber) AND redscore < bluescore) OR ((blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber)) AND bluescore < redscore) AND complevel = 10 AND event = $id";
			$tie_query_filter = "SELECT * FROM matches WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber OR blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber) AND bluescore = redscore)) AND bluescore > -1 AND redscore > -1 AND complevel = 10 AND event = $id";
			break;
			
		case "elims":
			$win_query_filter = "SELECT * FROM matches WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber) AND redscore > bluescore) OR ((blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber) AND bluescore > redscore)) AND complevel > 10 AND event = $id";
			$lose_query_filter = "SELECT * FROM matches WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber) AND redscore < bluescore) OR ((blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber)) AND bluescore < redscore) AND complevel > 10 AND event = $id";
			$tie_query_filter = "SELECT * FROM matches WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber OR blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber) AND bluescore = redscore)) AND bluescore > -1 AND redscore > -1 AND complevel > 10 AND event = $id";
			break;
		
		case "event":
			$win_query_filter = "SELECT * FROM matches WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber) AND redscore > bluescore) OR ((blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber) AND bluescore > redscore)) AND event = $id";
			$lose_query_filter = "SELECT * FROM matches WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber) AND redscore < bluescore) OR ((blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber)) AND bluescore < redscore) AND event = $id";
			$tie_query_filter = "SELECT * FROM matches WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber OR blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber) AND bluescore = redscore)) AND bluescore > -1 AND redscore > -1 AND event = $id";
			break;
			
		case "year":
			$win_query_filter = "SELECT * FROM matches, events WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber) AND redscore > bluescore) OR ((blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber) AND bluescore > redscore)) AND matches.event = events.eventid AND events.year = $id AND events.official = 1";
			$lose_query_filter = "SELECT * FROM matches, events WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber) AND redscore < bluescore) OR ((blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber)) AND bluescore < redscore) AND matches.event = events.eventid AND events.year = $id AND events.official = 1";
			$tie_query_filter = "SELECT * FROM matches, events WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber OR blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber) AND bluescore = redscore)) AND bluescore > -1 AND redscore > -1 AND matches.event = events.eventid AND events.year = $id AND events.official = 1";
			break;
			
		case "alltime":
			$win_query_filter = "SELECT * FROM matches, events WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber) AND redscore > bluescore) OR ((blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber) AND bluescore > redscore)) AND matches.event = events.eventid AND events.official = 1";
			$lose_query_filter = "SELECT * FROM matches, events WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber) AND redscore < bluescore) OR ((blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber)) AND bluescore < redscore) AND matches.event = events.eventid AND events.official = 1";
			$tie_query_filter = "SELECT * FROM matches, events WHERE (((red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber OR blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber) AND bluescore = redscore)) AND bluescore > -1 AND redscore > -1 AND matches.event = events.eventid AND events.official = 1";
			break;
	}
		
	$record_win_query = mysql_query($win_query_filter);
	$record["win"] = mysql_num_rows($record_win_query);
	
	$record_lose_query = mysql_query($lose_query_filter);
	$record["lose"] = mysql_num_rows($record_lose_query);
	
	$record_tie_query = mysql_query($tie_query_filter);
	$record["tie"] = mysql_num_rows($record_tie_query);
	
	return $record;
}

function stringWLT($record) {
	return "(" . $record["win"] . "-" . $record["lose"] . "-" . $record["tie"] . ")";
}

function getHighestMatch($eventid, $mode, $teamnumber) {
	//import global dictionaries
	global $complevelnames, $complevelnouns;

	//grab the event info
	$event_query_filter = "SELECT complevel, red1, red2, red3, blue1, blue2, blue3, redscore, bluescore FROM matches WHERE matches.event=$eventid AND (red1 = $teamnumber OR red2 = $teamnumber OR red3 = $teamnumber OR blue1 = $teamnumber OR blue2 = $teamnumber OR blue3 = $teamnumber) ORDER BY matches.complevel DESC, matches.matchnumber DESC LIMIT 1";
	$event_query = mysql_query($event_query_filter);
	$s = mysql_fetch_array($event_query);
	$complevel = $s["complevel"];
	
	if ($complevel == 50) {
		$red1 = $s["red1"];
		$red2 = $s["red2"];
		$red3 = $s["red3"];
		$blue1 = $s["blue1"];
		$blue2 = $s["blue2"];
		$blue3 = $s["blue3"];
		$redscore = $s["redscore"];
		$bluescore= $s["bluescore"];

		if (($red1 == $teamnumber OR $red2 == $teamnumber OR $red3 == $teamnumber) AND ($redscore > $bluescore)) {
			$complevel = 60;
		} elseif (($blue1 == $teamnumber OR $blue2 == $teamnumber OR $blue3 == $teamnumber) AND ($bluescore > $redscore)) {
			$complevel = 60;
		}
	}
	
	switch($mode) {
		case "string":
			return $complevelnouns[$complevel];
			break;
		default:
			return $complevel;
			break;
	}
}

////
// outputVerboseWLT
////
//This outputs a string similar to: "Team 88 was (5-4-1) at the New Jersey Regional in 2007. They were (5-2-1) in qualifications and (0-2-0) in elimination matches."
////

function outputVerboseWLT($eventid, $teamnumber) {
	//grab the event info
	$event_query_filter = "SELECT events.name, events.year, attendance.event FROM events, attendance WHERE attendance.event=events.eventid AND attendance.team = '$teamnumber' AND events.eventid = '$eventid'";
	$event_query = mysql_query($event_query_filter);
	while($s=mysql_fetch_array($event_query)) {
		$eventname = $s["name"];
		$eventyear = $s["year"];
	}
	$record = getWLT("event", $eventid, $teamnumber);
	//echo the event info.
	?><p><strong>Team <? echo $teamnumber ?></strong> was <strong>(<? echo $record["win"] . "-" . $record["lose"] . "-" . $record["tie"]?>)</strong> at the <?echo $eventname ?> in <?echo $eventyear?>. 
	<?	$elims_record = getWLT("elims", $eventid, $teamnumber);
		if ($elims_record["win"] > 0 OR $elims_record["lose"] > 0 OR $elims_record["tie"] > 0) {
			$quals_record = getWLT("quals", $eventid, $teamnumber);
			?>
			They were <strong>(<? echo $quals_record["win"] . "-" . $quals_record["lose"] . "-" . $quals_record["tie"]?>)</strong> in qualifications and <strong>(<? echo $elims_record["win"] . "-" . $elims_record["lose"] . "-" . $elims_record["tie"]?>)</strong> in elimination matches.
			<?
		}
	?></p><?
}

////
// hasMatches
////
//This determines if an event has any matches in the system. returns 1 or 0 correspondingly.
////

function hasMatches($eventid) {
	$has_matches_query_filter = "SELECT matches.complevel FROM events, matches WHERE events.eventid = matches.event AND events.eventid='$eventid' LIMIT 1";
	$has_matches_query = mysql_query($has_matches_query_filter);
	if (mysql_num_rows($has_matches_query) > 0) {
		return 1;
	} else {
		return 0;
	}
}

////
// outputMatches
////
//This outputs a table of matches from an event based on a team number, or team number "0" for "all matches"
////

function outputMatches($eventid, $teamnumber=0) {

	global $complevelnames, $complevelshort, $weeknames;
	
	//look up what event we're dealing with
	$eventinfo_query_filter = "SELECT name, year, eventshort FROM events WHERE eventid='$eventid'";
	$eventinfo_query = mysql_query($eventinfo_query_filter);
	$eventinfo = mysql_fetch_row($eventinfo_query);
	$eventname = $eventinfo[0];
	$eventyear = $eventinfo[1];
	$eventshort = $eventinfo[2];
	
	$has_matches = hasMatches($eventid);
	if ($has_matches > 0) {
	
		//set up the HTML table
		?><p>If matches are available to watch online, they will be indicated with a <img src="images/video_icon.png"> icon. If they are available for download, you may click on the <img src="images/download.png"> icon to download them directly from our site.</p>
		<table class="table_alt"><tr class="table_toprow"><td><img src="images/video_icon.png" /></td><td><img src="images/download.png" /></td><td>Match Number</td><td colspan="3">Red Alliance</td><td colspan="3">Blue Alliance</td><td colspan="2">Scores</td></tr><?
		
		for ($lookup_comp_level = 10; $lookup_comp_level < 60; $lookup_comp_level += 10) {
				
			//look up the matches for the event at this current $lookup_comp_level
			$match_query_filter = "SELECT * FROM `matches` WHERE `event`='$eventid' AND `complevel` = $lookup_comp_level";
			if ($teamnumber > 0) $match_query_filter = $match_query_filter . " AND (red1 = '$teamnumber' OR red2 = '$teamnumber' OR red3 = '$teamnumber' OR blue1 = '$teamnumber' OR blue2 = '$teamnumber' OR blue3 = '$teamnumber')";
			$match_query_filter = $match_query_filter . " ORDER BY `matchnumber` ASC";
			$match_query = mysql_query($match_query_filter);
			
			if (mysql_num_rows($match_query) > 0) {
				echo "<tr class=\"table_toprow\"><td colspan=\"11\" >{$complevelnames[$lookup_comp_level]}</td></tr>";
			}
			
			$i = 0;
			//Iterate through the matches and echo information
			while($r=mysql_fetch_array($match_query)) {
				$vidpath = videopath($eventshort, $eventyear, $r["complevel"], $r["matchnumber"], $r["vidext"]);
				$matchname = matchname($r["complevel"], $r["matchnumber"]);
				//the format is $variable = $r["nameofmysqlcolumn"];
				$i++;
				if ($r["redscore"] == (-1)) $r["redscore"] = "?";
				if ($r["bluescore"] == (-1)) $r["bluescore"] = "?";
				echo "<tr class=\"table_row".($i & 1)."\">";
				//is there flash?
				if ($r["flvup"] == 1) {
					echo "<td><a href=\"match.php?matchid={$r["matchid"]}\"><img src=\"images/video_icon.png\" alt=\"watch match online\"></a></td>";
				} else {
					echo "<td><img src=\"images/download_pad.png\" alt=\"no online video available\"></td>";
				} 
				//is there video?
				if ($r["vidup"] == 1) {
					echo "<td><a href=\"{$vidpath}\" title=\"Download - {$matchname} - {$currentevent} ({$currentyear})\" class=\"downloadlink\"><img src=\"images/download.png\" alt=\"download\"></a></td>";
				} else {
					echo "<td><img src=\"images/download_pad.png\" alt=\"no download available\"></td>";
				} 
				//link to the video page
				echo "<td><a href=\"match.php?matchid={$r["matchid"]}\" title=\"{$matchname} - {$eventname} ({$eventyear})\">{$matchname}</a></td>";
				//show players and winners
				if ($r["redscore"] > $r["bluescore"]) {
					echo "<td class=\"redcell\"><strong>" . teamlink($r["red1"],1) . "</strong></td>";
					echo "<td class=\"redcell\"><strong>" . teamlink($r["red2"],1) . "</strong></td>";
					echo "<td class=\"redcell\"><strong>" . teamlink($r["red3"],1) . "</strong></td>";
					echo "<td class=\"bluecell\">" . teamlink($r["blue1"],1) . "</td>";
					echo "<td class=\"bluecell\">" . teamlink($r["blue2"],1) . "</td>";
					echo "<td class=\"bluecell\">" . teamlink($r["blue3"],1) . "</td>";
					echo "<td class=\"redscorecell\"><strong>" . $r["redscore"] . "</strong></td>";
					echo "<td class=\"bluescorecell\">" . $r["bluescore"] . "</td>";
				} elseif ($r["bluescore"] > $r["redscore"]) {
					echo "<td class=\"redcell\">" . teamlink($r["red1"],1) . "</td>";
					echo "<td class=\"redcell\">" . teamlink($r["red2"],1) . "</td>";
					echo "<td class=\"redcell\">" . teamlink($r["red3"],1) . "</td>";
					echo "<td class=\"bluecell\"><strong>" . teamlink($r["blue1"],1) . "</strong></td>";
					echo "<td class=\"bluecell\"><strong>" . teamlink($r["blue2"],1) . "</strong></td>";
					echo "<td class=\"bluecell\"><strong>" . teamlink($r["blue3"],1) . "</strong></td>";
					echo "<td class=\"redscorecell\">" . $r["redscore"] . "</td>";
					echo "<td class=\"bluescorecell\"><strong>" . $r["bluescore"] . "</strong></td>";
				} elseif ($r["bluescore"] == $r["redscore"]) {
					echo "<td class=\"redcell\">" . teamlink($r["red1"],1) . "</td>";
					echo "<td class=\"redcell\">" . teamlink($r["red2"],1) . "</td>";
					echo "<td class=\"redcell\">" . teamlink($r["red3"],1) . "</td>";
					echo "<td class=\"bluecell\">" . teamlink($r["blue1"],1) . "</td>";
					echo "<td class=\"bluecell\">" . teamlink($r["blue2"],1) . "</td>";
					echo "<td class=\"bluecell\">" . teamlink($r["blue3"],1) . "</td>";
					echo "<td class=\"redscorecell\">" . $r["redscore"] . "</td>";
					echo "<td class=\"bluescorecell\">" . $r["bluescore"] . "</td>";
				}
				echo "</tr>";
			}
		}
		?></table><? //end the HTML table
	} else {
		?><p>No matches have been played yet.</p><?
	}
}

////
//events_for_week
////
//This outputs an array of eventids that are occuring in the specified week
////

function events_for_week($week)
{
	$filter = "SELECT * from events WHERE week = {$week}";
	$query = mysql_query($filter);
	$events = array(); //this holds our list of events
	while ($event = mysql_fetch_array($query))
	{
		$events[] = $event["eventid"];
	}
	
	return $events;
}

////
//current_week
////
//This gives us a week number (10 through 60, 10-step), or -1 if there is no week associated with the current date.
////

function current_week()
{
	global $week_definitions;
	$date = time();
	//if there are week definitions for the current year
	if (array_key_exists(date('Y'), $week_definitions))
	{
		$current_year = $week_definitions[date('Y')];
		//loop through all the elements of $current_year and check if the date is between the start/end dates of these weeks
		foreach ($current_year as $week => $dates)
		{
			$start = strtotime($dates[0]);
			$end = strtotime($dates[1] . "+1 day"); //otherwise saturday at 12a is considered the end of an event
			if (($date <= $end) && ($date >= $start))
			{
				//the current date is in between the start and end dates of this week
				return $week;
			}
		}
	}
	
	//if all else fails, return invalid week
	return -1;
}

////
// outputHighestScoringMatches
////
//This outputs a table of the highest scoring matches
////

///I temporarily abandon this until I can think of a clean way to sort by two columns.

function outputHighestScoringMatches($mode, $id, $number) {

//Mode can be "event", "year", "team".
//$id is then "eventid", "year", "teamnumber"
//$number is how many top matches you want.

	global $complevelnames, $complevelshort, $weeknames;

	//set up the HTML table
	?> <table class="table_alt"><tr class="table_toprow"><td><img src="images/video_icon.png" /></td><td><img src="images/download.png" /></td><td>Match</td><td>Event</td><td colspan="3">Red Alliance</td><td colspan="3">Blue Alliance</td><td colspan="2">Scores</td></tr><?
			
		//figure out which SQL statement to use
		
		switch($mode) {
			case "event":
				$match_query_filter = "SELECT * FROM `matches` WHERE `event`='$eventid' ORDER BY redscore ASC ";
			case "year":
			
			case "team":
		
		
		
		$match_query = mysql_query($match_query_filter);
		
		if (mysql_num_rows($match_query) > 0) {
			echo "<tr class=\"table_toprow\"><td colspan=\"11\" >{$complevelnames[$lookup_comp_level]}</td></tr>";
		}
		
		$i = 0;
		//Iterate through the matches and echo information
		while($r=mysql_fetch_array($match_query)) {
			$vidpath = videopath($eventshort, $eventyear, $r["complevel"], $r["matchnumber"], $r["vidext"]);
			$matchname = matchname($r["complevel"], $r["matchnumber"]);
			//the format is $variable = $r["nameofmysqlcolumn"];
			$i++;
			echo "<tr class=\"table_row".($i & 1)."\">";
			//is there flash?
			if ($r["flvup"] == 1) {
				echo "<td><a href=\"match.php?matchid={$r["matchid"]}\"><img src=\"images/video_icon.png\" alt=\"watch match online\"></a></td>";
			} else {
				echo "<td><img src=\"images/download_pad.png\" alt=\"no online video available\"></td>";
			} 
			//is there video?
			if ($r["vidup"] == 1) {
				echo "<td><a href=\"{$vidpath}\" title=\"Download - {$matchname} - {$currentevent} ({$currentyear})\" class=\"downloadlink\"><img src=\"images/download.png\" alt=\"download\"></a></td>";
			} else {
				echo "<td><img src=\"images/download_pad.png\" alt=\"no download available\"></td>";
			} 
			//link to the video page
			echo "<td><a href=\"match.php?matchid={$r["matchid"]}\" title=\"{$matchname} - {$eventname} ({$eventyear})\">{$matchname}</a></td>";
			//show players and winners
			if ($r["redscore"] > $r["bluescore"]) {
				echo "<td class=\"redcell\"><strong>" . teamlink($r["red1"],1) . "</strong></td>";
				echo "<td class=\"redcell\"><strong>" . teamlink($r["red2"],1) . "</strong></td>";
				echo "<td class=\"redcell\"><strong>" . teamlink($r["red3"],1) . "</strong></td>";
				echo "<td class=\"bluecell\">" . teamlink($r["blue1"],1) . "</td>";
				echo "<td class=\"bluecell\">" . teamlink($r["blue2"],1) . "</td>";
				echo "<td class=\"bluecell\">" . teamlink($r["blue3"],1) . "</td>";
				echo "<td class=\"redscorecell\"><strong>" . $r["redscore"] . "</strong></td>";
				echo "<td class=\"bluescorecell\">" . $r["bluescore"] . "</td>";
			} elseif ($r["bluescore"] > $r["redscore"]) {
				echo "<td class=\"redcell\">" . teamlink($r["red1"],1) . "</td>";
				echo "<td class=\"redcell\">" . teamlink($r["red2"],1) . "</td>";
				echo "<td class=\"redcell\">" . teamlink($r["red3"],1) . "</td>";
				echo "<td class=\"bluecell\"><strong>" . teamlink($r["blue1"],1) . "</strong></td>";
				echo "<td class=\"bluecell\"><strong>" . teamlink($r["blue2"],1) . "</strong></td>";
				echo "<td class=\"bluecell\"><strong>" . teamlink($r["blue3"],1) . "</strong></td>";
				echo "<td class=\"redscorecell\">" . $r["redscore"] . "</td>";
				echo "<td class=\"bluescorecell\"><strong>" . $r["bluescore"] . "</strong></td>";
			} elseif ($r["bluescore"] == $r["redscore"]) {
				echo "<td class=\"redcell\">" . teamlink($r["red1"],1) . "</td>";
				echo "<td class=\"redcell\">" . teamlink($r["red2"],1) . "</td>";
				echo "<td class=\"redcell\">" . teamlink($r["red3"],1) . "</td>";
				echo "<td class=\"bluecell\">" . teamlink($r["blue1"],1) . "</td>";
				echo "<td class=\"bluecell\">" . teamlink($r["blue2"],1) . "</td>";
				echo "<td class=\"bluecell\">" . teamlink($r["blue3"],1) . "</td>";
				echo "<td class=\"redscorecell\">" . $r["redscore"] . "</td>";
				echo "<td class=\"bluescorecell\">" . $r["bluescore"] . "</td>";
			}
			echo "</tr>";
		}
	}
	?></table><? //end the HTML table
}

?>